
package org.sopt.dev.ImgKnight.agent.Executor;

import java.util.List;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.apache.log4j.Logger;

import org.sopt.dev.ImgKnight.agent.Agent;

public class TakeUrlCompletionHandler implements Runnable {

	private Agent agent = null;
	
	private Logger exceptionLogger = null;
	
	public TakeUrlCompletionHandler() {
		this.agent = Agent.getInstance();
		exceptionLogger = Logger.getLogger("agent.exception");
	}
	
	@Override
	public void run() {
		CompletionService<List<String>> takeUrlcompletionService 
			= agent.getTakeUrlcompletionService();
		while( true ) {
			try {
				Future<List<String>> future = takeUrlcompletionService.take();
				if( future == null )
					continue;	
				List<String> extracted = future.get();
				if( extracted != null ) {
					if( extracted.size() > 0 ) {
						/*for(final String url : extracted) {
							serviceLogger.debug(url);
						}*/
					}
					agent.onCrawled(extracted);
					extracted.clear();
				}
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
				return;
			} catch (ExecutionException e) {
				exceptionLogger.warn("ExecutionException: "+e.toString());
				e.printStackTrace();
				agent.onMissedCrawl();
			}
		}
	}
	
}
